package handler

import (
	"encoding/json"
	"fmt"
	"hero/models"
	"net/http"
)

// Response 结构体用于封装JSON数据
type Response struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
}

type StudentHandler struct{}

// ServeHTTP 实现 hero.Handler 接口
func (h *StudentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	studentModel := &models.Student{}
	studentList := studentModel.GetList()
	response := Response{
		Code: http.StatusOK,
		Data: studentList,
	}
	jsonData, err := json.Marshal(response)
	if err != nil {
		fmt.Println("Error encoding JSON:", err)
		return
	}

	// 设置响应头，指定内容类型application/json
	w.Header().Set("Content-Type", "application/json")

	// 发送json作为响应
	_, err = w.Write(jsonData)
	if err != nil {
		http.Error(w, "Error writing response", http.StatusInternalServerError)
		return
	}
}
